﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IceScream.Models;
using IceScream.ViewModels;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using IceScream.Common;

namespace IceScream.Controllers
{
    [Authorize(Users = "Admin")]
    public class ProductManagerController : Controller
    {
        const string pathImage = "../Content/images/Products";
        string currentFile = "";

        DataEntities storeDB = new DataEntities();

        public ActionResult Index()
        {
            var Prods = storeDB.Products.ToList();
            return View(Prods);
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult Create()
        {
            var cats = storeDB.Categories.ToList();
            var viewModel = new ProductManagerViewModel
            {
                lstCategory = cats,
                sup_Product = new Product()
            };
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Create(IEnumerable<HttpPostedFileBase> Image, Product product, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    foreach (var file in Image)
                    {
                        if (file != null)
                        {
                            currentFile = file.FileName;

                            //get all file to know if it exists?
                            // if exists -> change name
                            string[] FileList = System.IO.Directory.GetFiles(Server.MapPath(pathImage));

                            currentFile = UICommon.ChangeFileName(FileList, currentFile);

                            var path = Path.Combine(Server.MapPath(pathImage), currentFile);
                            file.SaveAs(path);

                            // resize images file
                            string OriginalImg = pathImage + "/" + currentFile;

                            currentFile = ResizeImg(OriginalImg, 100, 80, pathImage);
                            // End resize
                            product.Image = "../" + pathImage + "/" + currentFile;
                        }
                    }

                    storeDB.AddToProducts(product);
                    storeDB.SaveChanges();
                    return RedirectToAction("Index");
                }
                var categories = storeDB.Categories.ToList();
                ProductManagerViewModel viewPro = new ProductManagerViewModel()
                {
                    sup_Product = new Product(),
                    lstCategory = categories
                };
                return View(viewPro);
            }
            catch
            {
                var categories = storeDB.Categories.ToList();
                ProductManagerViewModel viewPro = new ProductManagerViewModel()
                {
                    sup_Product = new Product(),
                    lstCategory = categories
                };
                return View(viewPro);
            }
        }

        public ActionResult Edit(int id)
        {
            Product pro = storeDB.Products.Where(s => s.Id == id).FirstOrDefault();
            ProductManagerViewModel viewPro = new ProductManagerViewModel() { 
                sup_Product = pro,
                lstCategory = storeDB.Categories.ToList()
            };

            return View(viewPro);
        }

        [HttpPost]
        public ActionResult Edit(IEnumerable<HttpPostedFileBase> Image, int id, FormCollection collection)
        {
            // TODO: Add update logic here
            var product = storeDB.Products.Where(s => s.Id == id).FirstOrDefault();
            if (ModelState.IsValid)
            {
                foreach (var file in Image)
                {
                    if (file != null)
                    {
                        try
                        {
                            // delete older file
                            string DeletePath = product.Image;
                            FileInfo deleteFile = new FileInfo(Server.MapPath(DeletePath));
                            deleteFile.Delete();
                        }
                        catch { }

                        currentFile = file.FileName;

                        //get all file to know if it exists?
                        // if exists -> change name
                        string pathImageEdit = pathImage.Remove(0, 2);
                        string[] FileList = System.IO.Directory.GetFiles(Server.MapPath(pathImageEdit));

                        currentFile = UICommon.ChangeFileName(FileList, currentFile);

                        // save file to database and upload to server
                        var path = Path.Combine(Server.MapPath(pathImageEdit), currentFile);
                        file.SaveAs(path);

                        //resize img
                        string OriginalImg = pathImageEdit + "/" + currentFile;
                        currentFile = ResizeImg(OriginalImg, 100, 80, pathImageEdit);

                        product.Image = "../.." + pathImageEdit + "/" + currentFile;
                    }
                    product.Description = HttpUtility.HtmlDecode(Request.Form["ctl00$AdminContent$Description"]);

                    UpdateModel(product, "sup_Product");
                    storeDB.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            ProductManagerViewModel viewPro = new ProductManagerViewModel()
            {
                sup_Product = product,
                lstCategory = storeDB.Categories.ToList()
            };

            return View(viewPro);
        }

        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here
                Product pro = storeDB.Products.Where(s => s.Id == id).FirstOrDefault();
                storeDB.Products.DeleteObject(pro);
                storeDB.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                Product pro = storeDB.Products.Where(s => s.Id == id).FirstOrDefault();
                storeDB.Products.DeleteObject(pro);
                storeDB.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        #region Helper 

        public string ResizeImg(string OriginalImg, int imageHeight, int imageWidth, string pathImageToResize)
        {
            Image fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(OriginalImg));
            Image.GetThumbnailImageAbort dummyCallBack = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Image thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero);
            DateTime myDate = DateTime.Now;
            string Mystring = myDate.ToString("ddMMyyhhmmss") + ".png";
            thumbNailImg.Save(Path.Combine(Server.MapPath(pathImageToResize), Mystring), ImageFormat.Jpeg);
            thumbNailImg.Dispose();

            fullSizeImg.Dispose();
            try
            {
                // delete older file
                FileInfo deleteFile = new FileInfo(Server.MapPath(OriginalImg));
                deleteFile.Delete();
            }
            catch { }

            return Mystring;
        }
        public bool ThumbnailCallback()
        {
            return false;
        }

        #endregion
    }
}
